package cn.wanda.bi.sunshine.platform.server.utils.exception;


import com.fasterxml.jackson.annotation.JsonProperty;

import cn.wanda.bi.sunshine.platform.server.SunshineCode;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;
import java.util.Arrays;

/**
 * Created by wangfupeng1
 */
@Data
public class SunshineException extends RuntimeException {

    private static final Logger logger = LoggerFactory.getLogger(SunshineExceptionHandler.class);

    private int status;
    private String message;
    private Object data;
    @JsonProperty("more info")
    private String moreInfo;

    static {
        Arrays.stream(SunshineCode.class.getDeclaredFields())
                .forEach(p -> {
                    try {
                        ErrorMessage annotation = p.getAnnotation(ErrorMessage.class);
                        System.setProperty(String.valueOf(p.get("value")), annotation.value());
                    } catch (Exception e) {
                        logger.error("fail to load error code:  " + p.getName());
                    }
                });
    }

    public SunshineException(int status, Object... msg) {
        String message = System.getProperty(String.valueOf(status));
        if (msg != null && msg.length > 0)
            message = MessageFormat.format(message, msg);
        this.status = status;
        this.message = message;
    }
}
